<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product extends CI_Controller {

	var $debug = '';
	var $per_page = '';

	public function __construct()
	{
		parent::__construct();	

		// gán giá trị tiêu đề form
		$this->template->set('nav',$this->uri->segment(1));
		$this->template->set('title', 'Sản phẩm');
		$this->template->set('section', 'Thông tin sản phẩm');

		$this->load->model('Dashboard_model');

		// load model storage
		$this->load->model('Storage_model');
		$this->load->model('Cron_model');
		$this->load->model('Product_model');
		$this->load->model('Product_images_model');
		$this->load->model('User_model');
		$this->load->model('Category_model');

		$this->load->model('Article_model');

		$this->load->helper(array('form', 'url'));
	}

	public function edit($id = false)
	{
		if(!$id)
		{
			redirect('dashboard/index');
		}

		$product = $this->Product_model->getEntry($id);

		if(empty($product))
		{
			redirect('dashboard/index');
		}

		$data['product'] = $product;
		$data['categories'] = $this->Category_model->getRecords();
		$data['user'] = $this->User_model->getUser($data['product']->user_id);

		// article
		$data['articles'] = $this->Article_model->infos($product->id);

		$this->template->load('admin/template','admin/editProduct',$data);
	}

	// add more images function
	public function addMoreImages($id = false)
	{
		$this->template->set('title', 'Thêm hình ảnh');
		$this->template->set('section', 'Thêm hình ảnh');

		if(!$id)
		{
			redirect('dashboard/index');
		}

		$product = $this->Product_model->getEntry($id);

		if(empty($product))
		{
			redirect('dashboard/index');
		}

		$data['product_id'] = $id;

		// get images of product
		$data['product_images'] = $this->Product_images_model->infos(array('product_id' => $product->id));		

		$this->template->load('admin/template','admin/addMoreImages',$data);
	}

	// upload image
	public function uploadImage($id = false)
	{
		$this->template->set('title', 'Thêm hình ảnh');
		$this->template->set('section', 'Thêm hình ảnh');

		if(!$id)
		{
			redirect('dashboard/index');
		}

		$product = $this->Product_model->getEntry($id);

		if(empty($product))
		{
			redirect('dashboard/index');
		}

		$is_uploadImage = $this->validate_image();

		if(!$is_uploadImage)
		{
			///////////// error upload //////////////////////////////////////
			$error_upload = $this->session->userdata('error_upload');

			if(!empty($error_upload))
				$data['error_upload'] = $error_upload;
			/////////////////////////////////////////////////////////////////			
		}
		else
		{			
			// resize image 182x250
			if(!empty($_FILES['userfile']['name']))
			{
				$this->resize_image($is_uploadImage, 620, 390);					
			}

			$data = array(
					'image'			=>	$is_uploadImage,
					'product_id'	=>	$product->id,
					'active'		=>	1,					
				);

			$this->Product_images_model->insert($data);
		}

		redirect('product/addMoreImages/'.$product->id);
	}


	public function deleteImage($id = false)
	{
		if(!$id)
		{
			redirect('dashboard/index');
		}
		$product_image = $this->Product_images_model->info(array('id'=>$id));

		if(empty($product_image))
		{
			redirect('dashboard/index');
		}

		$product_id = $product_image->product_id;

		$this->Product_images_model->delete($product_image->id);

		redirect('product/addMoreImages/'.$product_id);
	}

	public function update($id = false)
	{
		$updateBtn = $this->input->post('updateBtn');

		if(!$id)
		{
			redirect('dashboard/index');
		}

		$product = $this->Product_model->getEntry($id);
		$data['categories'] = $this->Category_model->getRecords();

		if(!empty($updateBtn))
		{
			$this->load->library('form_validation');

			$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
			$this->form_validation->set_rules('code', 'Code', 'trim|required');
			$is_uploadImage = $this->validate_image();
			//$this->form_validation->set_rules('price', 'Price', 'trim|required');
			//$this->form_validation->set_rules('description', 'Description', 'trim|required');


			if ($this->form_validation->run() == FALSE || !$is_uploadImage)
			{				
				///////////// error upload //////////////////////////////////////
				$error_upload = $this->session->userdata('error_upload');

				if(!empty($error_upload))
					$data['error_upload'] = $error_upload;
				/////////////////////////////////////////////////////////////////

				$product = $this->Product_model->getEntry($id);

				$data['product'] = $product;
				$data['user'] = $this->User_model->getUser($data['product']->user_id);						

				$this->template->load('admin/template','admin/editProduct',$data);
			}
			else
			{				
				$title = $this->input->post('title');
				$slug = $this->accents->removeaccents($title);
				$slug = url_title($slug);							    

				$sale_start = $this->input->post('sale_start');
				$sale_start = date('Y-m-d', strtotime($sale_start));

				$sale_end = $this->input->post('sale_end');
				$sale_end = date('Y-m-d', strtotime($sale_end));			

				$user_id = $this->input->post('user_id');	

				$category_id = $this->input->post('category_id');

				// update product
				$data = array(
						'title'			=>	$title,
						'code'			=>	$this->input->post('code'),
						'color_code'	=>	$this->input->post('color_code'),
						'category_id'	=>	$category_id,
						'slug'			=>	$slug,
						'image'			=>	empty($_FILES['userfile']['name']) ? $product->image : $is_uploadImage,
						'price'			=>	$this->input->post('price'),
						'description'	=>	$this->input->post('description'),
						'sale_price'	=>	$this->input->post('price_sale'),						
						'sale_start'	=>	$sale_start,
						'sale_end'		=>	$sale_end,
						'description'	=>	$this->input->post('description'),
						'active'		=>	$this->input->post('active'),
					);	

				// resize image 182x250
				if(!empty($_FILES['userfile']['name']))
				{
					$this->resize_image($is_uploadImage, 182, 250);					
				}

				// if user is empty, then no insert
				if(!empty($user_id))
					$data['user_id'] = $user_id;

				$this->Product_model->update($data, $id);	


				$this->session->set_userdata('notify_product', 'Sản phẩm '.$title.' cập nhật thành công');
				$this->session->set_userdata('notify_search', $title);

				redirect('dashboard/index','refresh');
			}
		}
		else
		{
			redirect('product/edit/'.$id);
		}
	}

	public function newProduct()
	{
		$this->load->library('form_validation');

		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('code', 'Code', 'trim|required');

		if ($this->form_validation->run() == FALSE)
		{										
			
		}
		else
		{
			// slug
			$title = $this->input->post('title');
			$slug = $this->accents->removeaccents($title);
			$slug = url_title($slug);

			$sale_start = $this->input->post('sale_start');
			$sale_start = date('Y-m-d', strtotime($sale_start));

			$sale_end = $this->input->post('sale_end');
			$sale_end = date('Y-m-d', strtotime($sale_end));


			$data = array(
					'title'			=>	$title,
					'slug'			=>	$slug,
					'code'			=>	$this->input->post('code'),
					'color'			=>	$this->input->post('color'),		
					'price' 		=>	$this->input->post('price'),
					'sale_price'	=>	$this->input->post('sale_price'),
					'user_id'		=>	$this->input->post('user_id'),
					'sale_start'	=>	$sale_start,
					'sale_end'		=>	$sale_end,
					'description'	=>	$this->input->post('description'),
				);

			$this->Product_model->insert($data);

			$this->session->set_userdata('notify_product', 'Sản phẩm '.$title.' tạo thành công');
			$this->session->set_userdata('notify_search', $title);
		}

		redirect('dashboard/index');
	}

	////////////////// make slug function ////////////////////////
	public function makeSlug()
	{
		$products = $this->Product_model->loadAll();

		foreach ($products as $row) 
		{
			$id = $row->id;
			$title = $row->title;

			$slug = $this->accents->removeaccents($title);
			$slug = url_title($slug);

			$data = array('slug' => $slug);

			$this->Product_model->update($data, $id);
		}

		redirect('dashboard/index');
	}

	//////////////////////////////////////////////////////////////

	public function validate_image()
	{
	    $config['upload_path'] = './uploads/image/products/';
	    $config['allowed_types'] = 'gif|jpg|png|jpg|jpeg';
	    $config['max_size']    = '10000';
	    $config['max_width']  = '10240';
	    $config['max_height']  = '7680';

	    $this->upload->initialize($config);

	    // if empty image upload then return true, since nothing to update
	    $image_upload = $_FILES['userfile']['name'];

	    if(empty($image_upload))
	    	return true;
	    
	    if (!$this->upload->do_upload('userfile'))
	    {
	        $this->session->set_userdata('error_upload', $this->upload->display_errors());
	        return false;
	    } else {
	    	$data = array('upload_data' => $this->upload->data());
	    	
	        return $data['upload_data']['file_name'];
	    }
	}	

	// resize image
	public function resize_image($uploaded_image,$width,$height)
	{
		$this->load->library('image_lib');

		$config['image_library'] = 'gd2';
		$config['source_image']	= './uploads/image/products/'.$uploaded_image;
		$config['create_thumb'] = false;
		$config['maintain_ratio'] = false;
		$config['width']	 = $width;
		$config['height']	= $height;

		$this->image_lib->clear();
	    $this->image_lib->initialize($config);
	    $this->image_lib->resize();
	}

	public function addArticle($product_id = false)
	{
		$data['product_id'] = $product_id;

		$addArticleBtn = $this->input->post('addArticleBtn');

		if(!empty($addArticleBtn))
		{
			$is_uploadImage = $this->validate_image();


			$data = array(
					'product_id'	=>	$product_id,
					'title'			=>	$this->input->post('title'),
					'detail'		=>	$this->input->post('detail'),
					'image'			=>	$is_uploadImage,
				);

			$this->Article_model->insert($data);

			// resize image 182x250
			if(!empty($_FILES['userfile']['name']))
			{
				$this->resize_image($is_uploadImage, 640, 426);					
			}

			redirect('product/edit/'.$product_id);
		}
		else
		{
			$this->template->load('admin/template','admin/addArticle',$data);
		}		
	}

	public function updateArticle($id = false)
	{

	}	
}	